package com.erf.controller;

import com.erf.domain.Order;
import com.erf.domain.User;
import com.erf.feign.ProviderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.net.URI;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;

@RestController
public class RestAndRibbonConsumer {
    @Value("${server.port}")
    private String port;
    @Autowired
    private DiscoveryClient discoveryClient;

    @Autowired
    private RestTemplate restTemplate;

    @GetMapping("/instances")
    public List<ServiceInstance> instances() {
        List<ServiceInstance> provider = this.discoveryClient.getInstances("provider");
        return provider;
    }

    /**
     * 使用restTemplate方式实现接口调用
     * 加上@LoadBalanced自后会导致该方法不可调用
     *
     * @return
     */
    @GetMapping("/indexRest")
    public String getIndex() {
        List<ServiceInstance> list = this.discoveryClient.getInstances("provider");
        int index = ThreadLocalRandom.current().nextInt(list.size());
        ServiceInstance serviceInstance = list.get(index);
        URI uri = serviceInstance.getUri();
        String url = uri + "/index";
        //restTemplate
        String result = restTemplate.getForObject(url, String.class);
        return "现在调用了consumer中restful的index，请求provider结果：" + result;
    }

    /**
     * ribbon不是alibaba组件，netflix的。包含于spring-boot-cloud
     * 默认轮循算法
     * ribbon是负载均衡算法（此处使用ribbon代替上面的Random获取随即节点），feign是声明式服务调用。
     */
    @GetMapping("/indexRibbon")
    public String getIndex2() {
        return "现在调用了consumer中restTemplate和ribbon的index，请求provider结果：" + this.restTemplate.getForObject("http://provider/index", String.class);
    }

    @GetMapping("/getOrder")
    public String getOrder() {
        return "现在调用了consumer:" + port + "中库存，请求provider订单结果：" + this.restTemplate.getForObject("http://provider/order", String.class);
    }

    @Autowired
    ProviderService providerService;
    @GetMapping("/testFeign")
    public void testFeign(){
        List<User> users = providerService.allUser();
        users.forEach(System.out::println);
    }

    @GetMapping("/testFeignAddOrder")
    public void testFeignAddOrder(){
        Order order = new Order(2,"订单2");
        int result = providerService.addOrder(order);
        System.out.println(result);
    }
}
